import 'dart:io';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:projectfluttershengyihuatong/category/CatetoryModel.dart';
import 'package:projectfluttershengyihuatong/service/jsontool.dart';
import 'package:projectfluttershengyihuatong/service/launchservice/launchservice.dart';
import 'package:projectfluttershengyihuatong/service/loginService/logginservice.dart';
import 'package:projectfluttershengyihuatong/service/request_manager.dart';
import 'package:projectfluttershengyihuatong/tab3/StudyListModel.dart';
import 'package:projectfluttershengyihuatong/tool/public_color.dart';
import 'package:projectfluttershengyihuatong/tool/tool.dart';
import 'package:projectfluttershengyihuatong/category/catetory_controller.dart';

class StudyPage extends StatefulWidget {
  const StudyPage({super.key});

  @override
  State<StudyPage> createState() => _StudyPageState();
}

class _StudyPageState extends State<StudyPage> {



  Future<List<CatetoryModel>?> requestCategory() async {
    final leimodel = CatetoryController.getInstance().leiModel;
    final pid = leimodel?.pid ?? 0;

    final url = LaunchService.getInstance().config?.api?.getLearnKemuList ?? "";

    final dict = {"project_id": pid};

    RequestManager
        .getInstance()
        .dio
        .options
        .headers["token"] = LoginService
        .getInstance()
        .userInfo
        ?.token ?? "";
    final response = await RequestManager.getInstance().dio.get(url, queryParameters: dict);

    final model = BaseModel<List<CatetoryModel>>.fromJson(response.data);


    return model.data;





  }


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(44),
        child: AppBar(
          title: Text("我的课程", style: TextStyle(color: Colors.white),),
          backgroundColor: primaryColor,
          actions: const [
            CalaenderBtn(),
          ],
        ),
      ),
      body: FutureBuilder(
        future: requestCategory(),
        builder: (context, snapshot){
          if (snapshot.hasData && snapshot.data != null) {
            final catetorys = snapshot.data ?? [];
            if (catetorys.isEmpty) {
              return Container(
                color: colorf9,
                child: const Center(
                  child: Text("暂时没有数据"),
                ),
              );
            }
            final tabs = catetorys.map((e){
              return Tab(text: e.title ?? "",);
            }).toList();
            final tabviews = catetorys.map((e){
              return StudyBottomWidget(pid: e.pid?.toInt() ?? 0);
            }).toList();
            return Container(
              color: colorf9,
              child: DefaultTabController(
                length: tabs.length,
                child: Column(
                  children: [
                    TabBar(
                      labelColor: primaryColor,
                      unselectedLabelColor: color33,
                      indicatorColor: primaryColor,
                      tabs: tabs,
                      isScrollable: true,
                      tabAlignment: TabAlignment.start,
                      dividerHeight: 0,
                    ),
                    Expanded(child: TabBarView(children: tabviews,
                    )),


                  ],
                ),
              ),
            );
          }
          return Container();
        },

      ),
    );
  }
}

class CalaenderBtn extends StatelessWidget {
  const CalaenderBtn({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return IconButton(onPressed: (){

    }, icon: Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Image.asset(assetImage("home-right-btn"), width: 20, fit: BoxFit.fitWidth,),
        const SizedBox(width: 5,),
        Text("直播日历", style: TextStyle(color: Colors.white),),
      ],
    ));
  }
}



class StudyBottomWidget extends StatefulWidget {
  const StudyBottomWidget({super.key, required this.pid});
  final int pid;

  @override
  State<StudyBottomWidget> createState() => _StudyBottomWidgetState();
}

class _StudyBottomWidgetState extends State<StudyBottomWidget> {

  Future<PageEntity<StudyListModel>?> refresh() async  {
    page = 1;
    final value = await request();
    return value;

  }


  Future<PageEntity<StudyListModel>?> request() async  {
    final params = {"kemu_id": widget.pid,"pageNo": page, "pageSize": 10};
    final url = LaunchService.getInstance().config?.api?.myCourseList ?? "";
    RequestManager.getInstance().dio.options.headers["token"] = LoginService.getInstance().userInfo?.token ?? "";
    final reponse = await RequestManager.getInstance().dio.get(url,queryParameters: params);
    final model = BaseModel<PageEntity<StudyListModel>>.fromJson(reponse.data);
    return model.data;

  }
  int page = 1;


  @override
  Widget build(BuildContext context) {
    return FutureBuilder(future: refresh(), builder:(context, snapshot){
      if (snapshot.hasData && snapshot.data != null) {
        final pageModel = snapshot.data;
        final total = pageModel?.total ?? 0;
        final dataArr = pageModel?.list ?? [];
        if (total > dataArr.length) {

        }else {
          return Container(
            color: colorf9,
            child: CustomScrollView(
              slivers: [
                    SliverPadding(
                      padding: const EdgeInsets.all(8),
                      sliver: SliverGrid(delegate: SliverChildBuilderDelegate(
                          (context,index){
                            final model = dataArr[index];
                            return ClipRRect(
                              borderRadius: BorderRadius.circular(6),
                              child: Container(
                                color: Colors.white,
                              
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Image.network(model.imgUrl ?? ""),
                                    
                                    Expanded(child: Padding(
                                      padding: const EdgeInsets.only(top: 8, left: 8),
                                      child: Text(model.name ?? ""),
                                    )),
                                    Expanded(child: Padding(
                                      padding: const EdgeInsets.only(left: 8,top: 3),
                                      child: Text(model.description ?? ""),
                                    )),
                                  ],
                                ),
                              ),
                            );
                          },
                        childCount: dataArr.length,
                      ), gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 2,
                        crossAxisSpacing: 8,

                        mainAxisSpacing: 10,
                        childAspectRatio: 10 / 9,
                      ),),
                    ),
                    SliverToBoxAdapter(
                      child: Container(height: 80,child: const Center(child: Text("没有更多数据"),),),
                    ),

                  ],
            ),
          );
        }




      }
      return  Container(
        color: Colors.white,
        child: const Center(
          child: Text("没有更多数据了"),
        ),
      );
    });
  }
}
